import { Address, toNano, fromNano, beginCell } from '@ton/core';
import { TonClient, WalletContractV4, internal } from "@ton/ton";
import { mnemonicNew, mnemonicToPrivateKey } from "@ton/crypto";
import { MyJettonMaster } from '../wrappers/MyJetton_MyJettonMaster';

const mainnet='https://toncenter.com/api/v2/jsonRPC';
const testnet='https://testnet.toncenter.com/api/v2/jsonRPC';

const mnemonic = "miss company tell wrong door ill crunch craft caution monkey humor impose century color urge company tennis detect public clinic win equal salad mix";
const mnemonic0 = "beach earn gallery pudding comic okay pistol jar broken venture corn clap social banner bonus pyramid claim demand index dad sort cabin imitate pulp";
const TONCONNECT_API_KEYS = "6fa2e5ce311c0ba4c3e25a0957620371ce8b62a24344dcc0e20b9d42b9b5dcb9";

export async function run() {
  await transferCoin();
}

export async function coinBalance() {
// Create Client
const client = new TonClient({
  endpoint: testnet,
});

// Generate new key
let keyPair = await mnemonicToPrivateKey(mnemonic0.split(' '));

// Create wallet contract
let workchain = 0; // Usually you need a workchain 0
let wallet = WalletContractV4.create({ workchain, publicKey: keyPair.publicKey });
let contract = client.open(wallet);

// Get balance
let balance: bigint = await contract.getBalance();
console.log('bal:'+balance);
}

export async function transferCoin(){
  const client = new TonClient({
    endpoint: testnet,
    apiKey: TONCONNECT_API_KEYS,
  });
  let keyPair = await mnemonicToPrivateKey(mnemonic.split(' '));
  let workchain = 0; // Usually you need a workchain 0
  let wallet = WalletContractV4.create({ workchain, publicKey: keyPair.publicKey });
  let contract = client.open(wallet);

  let seqno: number = await contract.getSeqno();
  let transfer = await contract.createTransfer({
    seqno,
    secretKey: keyPair.secretKey,
    messages: [internal({
      value: '0.05',
      to: '0QAKRJsZhhJGouqbtTpvXOjR9nB2ixjoCKHhmG2Nc1fcPT58',
      body: 'Hello world',
    })]
  });
  
  await contract.send(transfer);
}